const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const es3ifyPlugin = require('es3ify-webpack-plugin');
const webpack = require('webpack');

const projectConfig = require("./project.config.json");
let entry = {},
  html = [];
pre_process();

module.exports = {
  mode: "development",
  entry: entry,
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name].[contenthash].js",
    clean: true,
  },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          ie8: true,
          mangle: true,
          output: {
            comments: false, //是否有注释
            beautify: true,
            quote_keys: true
          },
          compress: {
            computed_props: false,
            properties: false,
            drop_console: false,
            warnings: false, //是否显示警告
          },
        },
        extractComments: false,
      }),
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: [
            "default",
            {
              discardComments: {
                removeAll: true,
              },
            },
          ],
        },
      }),
    ],
  },
  devtool: "source-map",
  plugins: [
    ...html,
    new MiniCssExtractPlugin(),
    new webpack.ProvidePlugin({
      $: 'jquery',
    }),
    new es3ifyPlugin()
  ],
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    // webpack5 需要的
    historyApiFallback: true,
    // webpack5 需要的
    allowedHosts: "all",
    proxy: [
      {
        context: ["/api"],
        target: "http://127.0.0.1:8090",
        changeOrigin: true,
      },
    ],
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: [
                [
                  "@babel/preset-env",
                  {
                    useBuiltIns: "entry",
                    corejs: 3,
                  },
                ],
              ],
              plugins: [
                ["@babel/plugin-transform-runtime"],
                [
                  // 笔者为了兼容IE8才用了这个插件，代价是不能tree shaking
                  // 没有IE8兼容需求的同学可以把这个插件去掉
                  '@babel/plugin-transform-modules-commonjs'
                ]
              ],
            },
          },
        ],
      },
      {
        test: /\.js$/,
        include: /node_modules\/axios/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: [
                [
                  "@babel/preset-env",
                  {
                    useBuiltIns: "entry",
                    corejs: 3,
                  },
                ],
              ],
              plugins: [
                ["@babel/plugin-transform-runtime"],
                [
                  // 笔者为了兼容IE8才用了这个插件，代价是不能tree shaking
                  // 没有IE8兼容需求的同学可以把这个插件去掉
                  '@babel/plugin-transform-modules-commonjs'
                ]
              ],
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          //   "style-loader",
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: [
                  [
                    "postcss-preset-env",
                    {
                      browsers: "ie >= 8",
                    },
                  ],
                ],
              },
            },
          },
        ],
      },
    ],
  },
  target: ["web", "es5"],
};

function pre_process() {
  if (projectConfig.components) {
    for (let key in projectConfig.components) {
      entry[key] = [].concat([projectConfig.components[key].js]);
      entry[key] = entry[key].concat([projectConfig.components[key].css]);
      html.push(
        new HtmlWebpackPlugin({
          template: projectConfig.components[key].html,
          chunks: [key, ...projectConfig.components[key]["vendorJs"]],
          chunksSortMode: function (a, b) {
            if (a.indexOf("common") !== -1) {
              return -1;
            }
            return 1;
          },
          filename: key + ".html",
        })
      );
    }
  }

  if (projectConfig.js) {
    for (let key in projectConfig.js) {
      entry[key] = projectConfig.js[key];
    }
  }

  for (const key in entry) {
    if (
      projectConfig.components[key] &&
      projectConfig.components[key]["vendorCss"].length > 0
    ) {
      let cssArray = projectConfig.components[key]["vendorCss"];
      for (const ele of cssArray) {
        entry[key] = [...entry[key], ...projectConfig.css[ele]];
      }
    }
  }
}
